package cn.tedu.lock;

import java.util.concurrent.Semaphore;

/**
 * 案例: 饭馆吃饭
 * 饭馆的桌子数量是有限的
 * 每过来一波客人就会占用一张桌子
 * 当桌子被全部占用后, 后来的客人需要等待
 * 直到有客人离开, 桌子被空出, 等待的客人才可以使用这张桌子用餐
 * 桌子 --- 信号 --- 限流
 */
public class SemaphoreDemo {
    public static void main(String[] args) {
        // 5个信号 --- 5张桌子
        Semaphore semaphore = new Semaphore(5);
        for (int i = 0; i < 20; ++i) {
            new Thread(new Eater(semaphore, (i + 1) + "号客人")).start();
        }
    }
}

class Eater implements Runnable {
    private Semaphore semaphore;
    private String eaterName;

    public Eater(Semaphore semaphore, String eaterName) {
        this.semaphore = semaphore;
        this.eaterName = eaterName;
    }

    @Override
    public void run() {
        try {
            semaphore.acquire();
            // 每过来一波客人就会占用一张桌子
            System.out.println("来了一波客人: " + eaterName + ", 占用了一张桌子");
            // 模拟就餐时间
            Thread.sleep((long) (Math.random() * 10000));
            // 用餐完成之后, 空出这张桌子
            System.out.println("客人" + eaterName + "用餐完毕, 起身离开, 空出一张桌子");
            semaphore.release();
        } catch (InterruptedException interruptedException) {
            interruptedException.printStackTrace();
        }
    }
}